package com.test.daily.leetcode.y2022.m05.day0518.v10;

/**
 * Solution
 *
 * @author Tom on 2022/5/18
 */
public class Solution {
    public static class Node {
        int value;
        Node next;

        public Node(int value) {
            this.value = value;
        }
    }

    public static Node listPartition1(Node head, int pivot) {
        Node cur = head;
        int i = 0;
        while (cur != null) {
            i++;
            cur = cur.next;
        }
        Node[] nodeArr = new Node[i];
        cur = head;
        for (int j = 0; j < i; j++) {
            nodeArr[j] = cur;
            cur = cur.next;
        }
        partition1(nodeArr, pivot);
        for (int j = 1; j < nodeArr.length; j++) {
            nodeArr[j - 1].next = nodeArr[j];
        }
        nodeArr[nodeArr.length - 1].next = null;
        return nodeArr[0];
    }

    public static void partition1(Node[] nodeArr, int pivot) {
        int L = -1;
        int index = 0;
        int R = nodeArr.length;
        while (index < R) {
            if (nodeArr[index].value == pivot) {
                index++;
            } else if (nodeArr[index].value < pivot) {
                swap(nodeArr, ++L, index++);
            } else {
                swap(nodeArr, index, --R);
            }
        }
    }

    public static void swap(Node[] nodeArr, int i, int j) {
        Node tmp = nodeArr[i];
        nodeArr[i] = nodeArr[j];
        nodeArr[j] = tmp;
    }

    public static Node listPartition(Node head, int pivot) {
        Node sH = null;
        Node sT = null;
        Node eH = null;
        Node eT = null;
        Node mH = null;
        Node mT = null;
        while (head != null) {
            Node next = head.next;
            if (head.value == pivot) {
                if (eH == null) {
                    eH = head;
                    eT = head;
                } else {
                    eT.next = head;
                    eT = sT.next;
                }
            } else if (head.value < pivot) {
                if (sH == null) {
                    sT = head;
                    sH = head;
                } else {
                    sT.next = head;
                    sT = sT.next;
                }
            } else {
                if (mH == null) {
                    mH = head;
                    mT = head;
                } else {
                    mT.next = head;
                    mT = mT.next;
                }
            }
            head = next;
        }
        if(sT != null){
            sT.next = eH == null ? mH : eH;
        }
        if(eH != null){
            eH.next = mH;
        }
        return sH != null ? sH: (eH != null? eH: mH);

    }
}
